from hashlib import md5
from google.appengine.api import memcache
import logging
from logging import error, info, debug
from google.appengine.api.labs import taskqueue

from models import Feed, FeedContent
from google.appengine.api import urlfetch
from google.appengine.api.urlfetch import InvalidURLError, DownloadError
from google.appengine.runtime import  DeadlineExceededError 
from google.appengine.runtime.apiproxy_errors import InterruptedError
import feedparser

import wsgiref.handlers
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
import datetime, re

cond = True
k = 0

while cond :
	feeds = Feed.all().fetch( 1000, k )
	for feed in feeds:
		content = FeedContent.all().filter( "feed =", feed ).order( "-date" ).fetch( 1 )
		
		print "<pre>"
		if ( len( content ) != 0 ):
			print content[0].date
		if len( content) ==0 or content[0].date is None or type(content[0].date).__name__ != 'datetime':
			continue

		p = re.compile( "(\d*) days" )
		days = p.search( str( datetime.datetime.now() - content[0].date ) )
		if days is None :
			daysStr = ""
		else:
			daysStr = days.group(1) 

		if daysStr == "":
			continue

		feed.weight = int( daysStr )
		feed.put()

	cond = False



